package com.netty.pro.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xuzn
 * @ClassName: NioCopyByBuffer
 * @ProjectName echo-project
 * @date 2020/3/5/7:57
 */
public class NioCopyByBuffer {

  public static void main(String[] args) throws Exception {
    // 创建输入流
    File file = new File("1.txt");
    FileInputStream fileInputStream = new FileInputStream(file);
    // 获取channel
    FileChannel fileInputStreamChannel = fileInputStream.getChannel();
    // 创建buffer
    ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
    // 创建输出流
    FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
    FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

    while (true) {
      // 将buffer进行复位
//      byteBuffer.clear();
      /**
       *public final Buffer clear() {
       *         position = 0; // 将position置为0
       *         limit = capacity;
       *         mark = -1;
       *         return this;
       *     }
       */
      // 将文件写入到buffer中
      int read = fileInputStreamChannel.read(byteBuffer);
      System.out.println("read=" + read);
      if (read == -1) {
        break;
      }
      // 转换buffer读写
      byteBuffer.flip();
      fileOutputStreamChannel.write(byteBuffer);
    }
    fileInputStream.close();
    fileOutputStream.close();
  }
}
